package com.mango.game.controller;

import com.mango.game.common.JwtTokenProvider;
import com.mango.game.dtos.JvmInfoDTO;
import com.mango.game.dtos.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.*;

@RestController
public class HelloController {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @GetMapping("/hello/health")
    public JvmInfoDTO health() {
        // 获取堆内存信息
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

        // 初始化JVMInfo对象
        JvmInfoDTO jvmInfo = new JvmInfoDTO();
        jvmInfo.setHeapMemoryUsed(heapMemoryUsage.getUsed());
        jvmInfo.setHeapMemoryTotal(heapMemoryUsage.getCommitted());
        jvmInfo.setNonHeapMemoryUsed(memoryMXBean.getNonHeapMemoryUsage().getUsed());
        jvmInfo.setMaxHeapMemory(heapMemoryUsage.getMax());

        // 获取线程信息
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        jvmInfo.setThreadCount(threadMXBean.getThreadCount());
        jvmInfo.setActiveThreadCount(threadMXBean.getDaemonThreadCount());

        // 获取类加载信息
        ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean();
        jvmInfo.setLoadedClassCount(classLoadingMXBean.getLoadedClassCount());

        return jvmInfo;
    }

    @GetMapping("/hello/token/{name}")
    public ResponseEntity<Object> token(@PathVariable("name") String name) {
        LoginUserDTO dto = new LoginUserDTO();
        dto.setUsername(name);
        dto.setNameSpace(1000000000000000000L);
        dto.setGameId(1000000000000000000L);
        dto.setChannelId(1000000000000000000L);
        dto.setProductsId(1000000000000000000L);
        dto.setUserId(1000000000000000000L);
        String token = jwtTokenProvider.generateToken(dto);
        return ResponseEntity.ok("Bearer " + token);
    }

}
